package com.apache.common.plugins;

import com.apache.api.vo.ParamsVo;
import com.apache.api.vo.ResultEntity;
import com.apache.cache.util.Validator;
import com.apache.ius.plugin.CustomMethodPlugin;
import com.apache.ius.plugin.IusPluginUtil;
import com.apache.ius.plugin.UtilPlugin;
import com.apache.tools.DataMap;
import com.apache.tools.DateUtils;
import com.apache.tools.FileOperate;
import com.apache.tools.StrUtil;
import com.apache.uct.common.ToolsUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.*;

/**
 * 平台版本升级检查 add 2020-09-15
 * 仅检查数据表、接口、插件、菜单、数据字典等配置，在上次更新时间之后所发生变化的数据
 */
public class PlateformVersionUpCheckPluginImpl implements CustomMethodPlugin {
    protected Logger log = LoggerFactory.getLogger(getClass());
    @Override
    public Object beforeInvoke(Map<String, Object> param) {
        String currentVersion = StrUtil.doNull(String.valueOf(param.get("currentVersion")),"");
        String sysEname = StrUtil.doNull(String.valueOf(param.get("searchSysEname")),"");
        String lastTime = StrUtil.doNull(String.valueOf(param.get("searchLastTime")),DateUtils.Now.fmt_yyyyMMdd_HHmmss());
        String databaseType = StrUtil.doNull(String.valueOf(param.get("databaseType")), "mysql");
        long lastTimeLong = DateUtils.strToLong(lastTime,DateUtils.FmtStr.yyyyMMdd_HHmmss);
        log.info("版本升级检查【"+sysEname+"】【"+lastTime+"】【"+lastTimeLong+"】start....");
        StringBuffer doc_content = new StringBuffer("-- version : ").append(currentVersion);
        doc_content.append("\n").append("-- check system : "+(StrUtil.isNull(sysEname)?"ALL":sysEname));
        doc_content.append("\n").append("-- check change after time : "+lastTime);
        doc_content.append("\n").append("-- create time : "+DateUtils.Now.fmt_yyyyMMdd_HHmmss());

        List<Map> resultList = new ArrayList<>();

        //检查-数据表配置表
        StringBuffer sql_sort_info = new StringBuffer("");
        sql_sort_info.append("select i.*");
        sql_sort_info.append(" from pub_sort_info i where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_sort_info.append(" and i.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_sort_info.append(" and unix_timestamp(i.create_time)>=unix_timestamp('"+lastTime+"')");
            sql_sort_info.append(" order by i.sys_name asc,unix_timestamp(i.create_time) desc");
        }else{
            sql_sort_info.append(" and i.create_time >='"+lastTime+"'");
            sql_sort_info.append(" order by i.sys_name asc,i.create_time desc");
        }
        List<DataMap> resultEntity_sort_info = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_sort_info.toString(),0,0);
        long total_sort_info = resultEntity_sort_info.size();
        log.info("检查到[pub_sort_info-数据表定义表]共计["+total_sort_info+"]条");
        if(total_sort_info>0){
            Map<String,Object> map_sort_info= new HashMap();
            map_sort_info.put("code","sortInfo");
            map_sort_info.put("title","数据表定义表");
            map_sort_info.put("total",total_sort_info);
            map_sort_info.put("rows",resultEntity_sort_info);
            resultList.add(map_sort_info);

            doc_content.append("\n\n").append("-- pub_sort_info");
            doc_content.append("\n").append(sql_sort_info).append(";");
        }

        //检查-数据表-字段配置表
        StringBuffer sql_pub_metadata_download = new StringBuffer("select d.*");
        StringBuffer sql_pub_metadata = new StringBuffer("select t.*,i.sort_name,i.info_table_name,i.sys_name from (");
        sql_pub_metadata.append(" select d.metadata_id,d.sort_id,d.data_short_name,d.data_attr,d.data_full_name,d.create_time");
        sql_pub_metadata.append(" from pub_metadata d where 1=1");
        sql_pub_metadata_download.append(" from pub_metadata d where 1=1");
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_pub_metadata.append(" and unix_timestamp(d.create_time)>=unix_timestamp('"+lastTime+"')");
            sql_pub_metadata.append(" order by d.sort_id,unix_timestamp(d.create_time) desc");

            sql_pub_metadata_download.append(" and unix_timestamp(d.create_time)>=unix_timestamp('"+lastTime+"')");
            sql_pub_metadata_download.append(" order by d.sort_id,unix_timestamp(d.create_time) desc");
        }else{
            sql_pub_metadata.append(" and d.create_time >='"+lastTime+"'");
            sql_pub_metadata.append(" order by d.sort_id desc,d.create_time desc");

            sql_pub_metadata_download.append(" and d.create_time >='"+lastTime+"'");
            sql_pub_metadata_download.append(" order by d.sort_id desc,d.create_time desc");
        }
        sql_pub_metadata.append(" ) t,pub_sort_info i");
        sql_pub_metadata.append(" where t.sort_id=i.sort_id");
        if(!StrUtil.isNull(sysEname)){
            sql_pub_metadata.append(" and i.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_pub_metadata.append(" order by i.sys_name asc,t.sort_id desc,unix_timestamp(t.create_time) desc");
        }else{
            sql_pub_metadata.append(" order by i.sys_name asc,t.sort_id desc,t.create_time desc ");
        }
        List<DataMap> resultEntity_pub_metadata = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_pub_metadata.toString(),0,0);
        long total_pub_metadata = resultEntity_pub_metadata.size();
        log.info("检查到[pub_metadata-字段配置表]共计["+total_pub_metadata+"]条");
        if(total_pub_metadata>0){
            Map<String,Object> map_pub_metadata= new HashMap();
            map_pub_metadata.put("code","metadata");
            map_pub_metadata.put("title","字段配置表");
            map_pub_metadata.put("total",total_pub_metadata);
            map_pub_metadata.put("rows",resultEntity_pub_metadata);
            resultList.add(map_pub_metadata);

            doc_content.append("\n\n").append("-- pub_metadata");
            doc_content.append("\n").append(sql_pub_metadata_download).append(";");
        }

        //检查-接口参数表
        StringBuffer sql_sys_param = new StringBuffer("");
        sql_sys_param.append("select m.*");
        sql_sys_param.append(" from sys_param_manager m where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_sys_param.append(" and m.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_sys_param.append(" and (unix_timestamp(m.create_time)>=unix_timestamp('"+lastTime+"') or unix_timestamp(m.modify_time)>=unix_timestamp('"+lastTime+"') )");
            sql_sys_param.append(" order by m.sys_name asc,unix_timestamp(m.modify_time) desc,unix_timestamp(m.create_time) desc");
        }else{
            sql_sys_param.append(" and (m.create_time >='"+lastTime+"' or m.modify_time >='"+lastTime+"')");
            sql_sys_param.append(" order by m.sys_name asc,m.modify_time desc,m.create_time desc");
        }
        List<DataMap> resultEntity_sys_param = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_sys_param.toString(),0,0);
        long total_sys_param = resultEntity_sys_param.size();
        log.info("检查到[sys_param_manager-接口配置参数表]共计["+total_sys_param+"]条");
        if(total_sys_param>0){
            Map<String,Object> map_sys_param_manager= new HashMap();
            map_sys_param_manager.put("code","sysParamManager");
            map_sys_param_manager.put("title","接口配置参数表");
            map_sys_param_manager.put("total",total_sys_param);
            map_sys_param_manager.put("rows",resultEntity_sys_param);
            resultList.add(map_sys_param_manager);

            doc_content.append("\n\n").append("-- sys_param_manager");
            doc_content.append("\n").append(sql_sys_param).append(";");
        }

        //检查-插件配置表
        StringBuffer sql_plugin_manager = new StringBuffer("");
        sql_plugin_manager.append("select p.*");
        sql_plugin_manager.append(" from sys_plugin_manager p where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_plugin_manager.append(" and p.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_plugin_manager.append(" and unix_timestamp(p.create_time)>=unix_timestamp('"+lastTime+"')");
            sql_plugin_manager.append(" order by p.sys_name asc,unix_timestamp(p.create_time) desc");
        }else{
            sql_plugin_manager.append(" and p.create_time >='"+lastTime+"'");
            sql_plugin_manager.append(" order by p.sys_name asc,p.create_time desc");
        }
        List<DataMap> resultEntity_plugin_manager = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_plugin_manager.toString(),0,0);
        long total_plugin_manager = resultEntity_plugin_manager.size();
        log.info("检查到[sys_plugin_manager-插件配置表]共计["+total_plugin_manager+"]条");
        if(total_plugin_manager>0){
            Map<String,Object> map_plugin_manager= new HashMap();
            map_plugin_manager.put("code","sysPluginManager");
            map_plugin_manager.put("title","插件配置表");
            map_plugin_manager.put("total",total_plugin_manager);
            map_plugin_manager.put("rows",resultEntity_plugin_manager);
            resultList.add(map_plugin_manager);

            doc_content.append("\n\n").append("-- sys_plugin_manager");
            doc_content.append("\n").append(sql_plugin_manager).append(";");
        }

        //检查-插件组合配置表
        StringBuffer sql_plugin_group = new StringBuffer("");
        sql_plugin_group.append("select p.*");
        sql_plugin_group.append(" from sys_plugin_group p where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_plugin_group.append(" and p.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_plugin_group.append(" and unix_timestamp(p.create_time)>=unix_timestamp('"+lastTime+"')");
            sql_plugin_group.append(" order by p.sys_name asc,unix_timestamp(p.create_time) desc");
        }else{
            sql_plugin_group.append(" and p.create_time >='"+lastTime+"'");
            sql_plugin_group.append(" order by p.sys_name asc,p.create_time desc");
        }
        List<DataMap> resultEntity_plugin_group = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_plugin_group.toString(),0,0);
        long total_plugin_group = resultEntity_plugin_group.size();
        log.info("检查到[sys_plugin_group-插件组合配置表]共计["+total_plugin_group+"]条");
        if(total_plugin_group>0){
            Map<String,Object> map_plugin_group= new HashMap();
            map_plugin_group.put("code","sysPluginGroup");
            map_plugin_group.put("title","插件组合配置表");
            map_plugin_group.put("total",total_plugin_group);
            map_plugin_group.put("rows",resultEntity_plugin_group);
            resultList.add(map_plugin_group);

            doc_content.append("\n\n").append("-- sys_plugin_group");
            doc_content.append("\n").append(sql_plugin_group).append(";");
        }

        //检查-菜单模块配置表
        StringBuffer sql_sys_module = new StringBuffer("");
        sql_sys_module.append("select m.*");
        sql_sys_module.append(" from sys_module m where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_sys_module.append(" and m.sys_name='"+sysEname+"'");
        }
        if("mysql".equalsIgnoreCase(databaseType)){
            sql_sys_module.append(" and (unix_timestamp(m.create_time)>=unix_timestamp('"+lastTime+"') or unix_timestamp(m.modify_time)>=unix_timestamp('"+lastTime+"') )");
            sql_sys_module.append(" order by m.sys_name asc,unix_timestamp(m.modify_time) desc,unix_timestamp(m.create_time) desc");
        }else{
            sql_sys_module.append(" and (m.create_time >='"+lastTime+"' or m.modify_time >='"+lastTime+"')");
            sql_sys_module.append(" order by m.sys_name asc,m.modify_time desc,m.create_time desc");
        }
        List<DataMap> resultEntity_sys_module = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_sys_module.toString(),0,0);
        long total_sys_module = resultEntity_sys_module.size();
        log.info("检查到[sys_module-菜单模块配置表]共计["+total_sys_module+"]条");
       if(total_sys_module>0){
           Map<String,Object> map_sys_module= new HashMap();
           map_sys_module.put("code","sysModule");
           map_sys_module.put("title","菜单模块配置表");
           map_sys_module.put("total",total_sys_module);
           map_sys_module.put("rows",resultEntity_sys_module);
           resultList.add(map_sys_module);

           doc_content.append("\n\n").append("-- sys_module");
           doc_content.append("\n").append(sql_sys_module).append(";");
       }

        //检查-数据字典表
        StringBuffer sql_dict_data_cate = new StringBuffer("");
        sql_dict_data_cate.append("select d.*");
        sql_dict_data_cate.append(" from dict_data_cate d where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_dict_data_cate.append(" and d.sys_ename='"+sysEname+"'");
        }
        sql_dict_data_cate.append(" and (d.create_time>='"+lastTimeLong+"' or d.update_time>='"+lastTimeLong+"')");
        sql_dict_data_cate.append(" order by d.sys_ename asc,d.update_time desc,d.create_time desc");
        List<DataMap> resultEntity_dict_data_cate = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_dict_data_cate.toString(),0,0);
        long total_dict_data_cate = resultEntity_dict_data_cate.size();
        log.info("检查到[dict_data_cate-数据字典表]共计["+total_dict_data_cate+"]条");
        if(total_dict_data_cate>0){
            Map<String,Object> map_dict_data_cate= new HashMap();
            map_dict_data_cate.put("code","dictDataCate");
            map_dict_data_cate.put("title","数据字典表");
            map_dict_data_cate.put("total",total_dict_data_cate);
            map_dict_data_cate.put("rows",resultEntity_dict_data_cate);
            resultList.add(map_dict_data_cate);

            doc_content.append("\n\n").append("-- dict_data_cate");
            doc_content.append("\n").append(sql_dict_data_cate).append(";");
        }

        //检查-数据字典条目明细表
        StringBuffer sql_dict_data_item = new StringBuffer("");
        sql_dict_data_item.append("select d.*");
        sql_dict_data_item.append(" from dict_data_item d where 1=1");
        if(!StrUtil.isNull(sysEname)){
            sql_dict_data_item.append(" and d.sys_name='"+sysEname+"'");
        }
        sql_dict_data_item.append(" and (d.create_time>='"+lastTimeLong+"' or d.update_time>='"+lastTimeLong+"')");
        sql_dict_data_item.append(" order by d.sys_name asc,d.cate_ename asc,d.update_time desc,d.create_time desc");
        List<DataMap> resultEntity_dict_data_item = (List<DataMap>)IusPluginUtil.getInstance().select("plateform",sql_dict_data_item.toString(),0,0);
        long total_dict_data_item = resultEntity_dict_data_item.size();
        log.info("检查到[dict_data_item-字典条目明细表]共计["+total_dict_data_item+"]条");
        if(total_dict_data_item>0){
            Map<String,Object> map_dict_data_item= new HashMap();
            map_dict_data_item.put("code","dictDataItem");
            map_dict_data_item.put("title","字典条目明细表");
            map_dict_data_item.put("total",total_dict_data_item);
            map_dict_data_item.put("rows",resultEntity_dict_data_item);
            resultList.add(map_dict_data_item);

            doc_content.append("\n\n").append("-- dict_data_item");
            doc_content.append("\n").append(sql_dict_data_item).append(";");
        }

        //把查询的SQL生成文件



        String msg = "查询成功";
        if(resultList.size()>0){
            String downloadPath = createExecScriptDoc(sysEname,lastTime,currentVersion,doc_content.toString());
            if(!StrUtil.isNull(downloadPath)){
                msg = downloadPath;
            }
        }
//        log.info("检查查询结果："+ JSONArray.fromObject(resultList));
        Map<String, Object> result = new HashMap<>(2);
        result.put(CustomMethodPlugin.resultMark, msg);
        result.put(CustomMethodPlugin.pluginInnerReturn, resultList);

        return result;
    }

    private String createExecScriptDoc(String sysEname,String lastTime,String currentVersion,String content){
        String nowTimeStr = DateUtils.format(new Date(),"yyyyMMddHHmmss");
        String fileUploadDirectory  =  ToolsUtil.getInstance().getLocalByKey("config.properties", "UPLOAD_DIRECTORY");//获取文件需要上传到的根目录
        String createFileRoot = "/atta/";// 创建文件的目录
        String fileDownloadUrl =  ToolsUtil.getInstance().getLocalByKey("config.properties", "DOWNLOAD_URL");//获取文件需要下载的根目录地址
        String fileName = "DS_v"+currentVersion+"_";
        if(!StrUtil.isNull(sysEname)){
            createFileRoot+=sysEname+"/";
            fileName+=sysEname+"_";
        }
        createFileRoot+="version/";
        fileName +=nowTimeStr+".txt";
        String filePathAll = fileUploadDirectory+createFileRoot;
        FileOperate.getInstance().newCreateFolder(filePathAll);//创建文件目录
        String downloadPath = fileDownloadUrl+createFileRoot+fileName;
        log.info("检查查询SQL[" + fileName + "]文件生成位置：" + filePathAll+fileName);
        boolean fileResult = FileOperate.getInstance().newCreateFile(filePathAll+fileName, content);
        log.info("检查查询SQL[" + fileName + "]文件下载地址：" + downloadPath);
        if(fileResult){
            return downloadPath;
        }
        return "";
    }

    @Override
    public Object doInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object afterInvoke(Map<String, Object> param) {
        // TODO Auto-generated method stub
        String orgId = String.valueOf(param.get("ids"));
        if ( Validator.isNotNull(orgId)) {
            Map<String,Object> deptMap = new HashMap<String,Object>();
            deptMap.put("uctDept.deptId",orgId);
            deptMap.put("uctDept.deptEname",orgId);
            deptMap.put("uctDept.deptCname","会员部");
            deptMap.put("uctDept.deptStatus",1);
            deptMap.put("uctDept.orgId",orgId);
            deptMap.put("uctDept.fatherId","0");
            deptMap.put("uctDept.orgEname",orgId);
            ResultEntity resultEntity = UtilPlugin.getInstance().saveByParams("platform","uctDept",deptMap);
        }
        return null;
    }

    /**
     * 规则校验入口（专门给系统公式规则提供的）
     *
     * @param paramsVo
     */
    public void run(ParamsVo paramsVo) {
        beforeInvoke(paramsVo.getParams());
    }

    public static void main(String[] args) {
        Date date = new Date();
        String createTime = DateUtils.getTime(date.toString());
        System.out.println(createTime);
    }
}
